<template>
  <d2-container>
    <template slot="header">指令自成交-修改</template>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">基础信息</p>
      </template>
      <el-form
        class="filter-container"
        ref="egForm"
        :rules="rules"
        :model="egForm"
        label-width="110px"
      >
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="匹配名称" prop="match_name">
              <el-input
                placeholder="请输入内容"
                v-model="egForm.match_name"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="匹配ID" prop="match_id">
              <el-input v-model="egForm.match_id" disabled> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="匹配说明">
              <el-input
                class="resizeNone"
                style="width:100%"
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="请输入内容"
                v-model="egForm.match_explain"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">交易信息</p>
      </template>
      <el-card shadow="never" class="d2-mb">
        <div style="margin-top:15px">
          <el-button size="small" style="margin-bottom:10px" @click="addRow_fn">
            增行
          </el-button>
          <el-button size="small" @click="delRow_fn">
            删行
          </el-button>
          <el-table
            :data="spotData"
            border
            :row-class-name="tableRow"
            fit
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="index" label="序号"> </el-table-column>
            <el-table-column type="selection" width="45"></el-table-column>

            <el-table-column prop="command_name" label="指令名称">
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.command_name"
                  placeholder="请输入内容"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="品名" width="160px">
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.productName"
                  disabled
                  style="width:70px"
                  placeholder="请输入内容"
                ></el-input>
                <!-- {{scope.row.name}} -->
                <el-button
                  size="small"
                  @click="select_fnn(scope.row.index, 'name')"
                  >选择</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="instrument" label="合约" width="160px">
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.instrument"
                  disabled
                  style="width:70px"
                  placeholder="请输入内容"
                ></el-input>
                <el-button
                  size="small"
                  @click="select_fnn(scope.row.index, 'instrument')"
                  >选择</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="direction" label="方向">
              <template slot-scope="scope">
                <el-select v-model="scope.row.direction" placeholder="请选择">
                  <el-option
                    v-for="item in directionSelect"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="offset_flag" label="开/平">
              <template slot-scope="scope">
                <el-select v-model="scope.row.offset_flag" placeholder="请选择" disabled>
                  <el-option
                    v-for="item in kp"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="volume" label="手数">
              <template slot-scope="scope">
                <el-input v-model="scope.row.volume" />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="成交价">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" />
              </template>
            </el-table-column>
            <el-table-column prop="real_account" label="柜台账户">
            </el-table-column>
            <el-table-column prop="sub_account" label="子账户">
            </el-table-column>
            <el-table-column prop="commodity_unit" label="单位">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.commodity_unit"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dw"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <el-button
        type="primary"
        size="small"
        style="float:right;margin:0 0 10px 10px;"
        @click="submit_fn"
      >
        保存
      </el-button>
      <el-button type="default" size="small" style="float:right">
        取消
      </el-button>
      <el-dialog
        title="指令明细选择"
        :visible.sync="dialogVisible"
        width="80%"
        :append-to-body="true"
      >
        <el-table
          :data="tableData"
          highlight-current-row
          @current-change="handleCurrentChange"
          style="width: 100%"
        >
          <el-table-column type="index" width="50px"> </el-table-column>
          <el-table-column prop="command_name" label="指令名称">
          </el-table-column>
          <el-table-column prop="command_id" label="指令ID">
          </el-table-column>
          <el-table-column prop="productName" label="品名"> </el-table-column>
          <el-table-column prop="instrument" label="合约"> </el-table-column>
          <el-table-column prop="direction" label="方向"> </el-table-column>
          <el-table-column prop="offset_flag" label="开/平"> </el-table-column>
          <el-table-column prop="volume" label="手数"> </el-table-column>
          <el-table-column label="成交价区间">
            <template slot-scope="scope">
              {{ scope.row.min_price }}-{{ scope.row.max_price }}
            </template>
          </el-table-column>
          <el-table-column prop="real_account" label="柜台账号">
          </el-table-column>
          <el-table-column prop="sub_account" label="子帐号"> </el-table-column>
          <el-table-column prop="commodity_unit" label="单位">
          </el-table-column>
          <el-table-column prop="currency" label="币种"> </el-table-column>
          <el-table-column prop="remarks" label="备注"> </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handlePaginationChange"
          :current-page.sync="pages.page"
          :page-size="pages.pageSize"
          layout="total, prev, pager, next"
          :total="pages.pageTotal"
        >
        </el-pagination>
        <div align="right">
          <el-button size="small" @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button size="small" @click="row_select_fn">选择</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="指令明细选择"
        :visible.sync="dialogVisible_addrow"
        width="80%"
      >
        <el-table
          :data="tableData_addrow"
          highlight-current-row
          @current-change="handleCurrentChange_addrow"
          style="width: 100%"
        >
          <el-table-column type="index" width="50px"> </el-table-column>
          <el-table-column prop="command_name" label="指令名称">
          </el-table-column>
          <el-table-column prop="command_id" label="指令ID">
          </el-table-column>
          <el-table-column prop="productName" label="品名"> </el-table-column>
          <el-table-column prop="instrument" label="合约"> </el-table-column>
          <el-table-column prop="direction" label="方向"> </el-table-column>
          <el-table-column prop="offset_flag" label="开/平"> </el-table-column>
          <el-table-column prop="volume" label="手数"> </el-table-column>
          <el-table-column label="成交价区间">
            <template slot-scope="scope">
              {{ scope.row.min_price }}-{{ scope.row.max_price }}
            </template>
          </el-table-column>
          <el-table-column prop="real_account" label="柜台账号">
          </el-table-column>
          <el-table-column prop="sub_account" label="子帐号"> </el-table-column>
          <el-table-column prop="commodity_unit" label="单位">
          </el-table-column>
          <el-table-column prop="currency" label="币种"> </el-table-column>
          <el-table-column prop="remarks" label="备注"> </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handlePaginationChange_addrow"
          :current-page.sync="pages.page"
          :page-size="pages.pageSize"
          layout="total, prev, pager, next"
          :total="pages.pageTotal"
        >
        </el-pagination>
        <div align="right">
          <el-button size="small" @click="dialogVisible_addrow = false"
            >取消</el-button
          >
          <el-button size="small" @click="addrow_select_fn">选择</el-button>
        </div>
      </el-dialog>
    </el-card>
  </d2-container>
</template>

<script>
import {
  command_self_info,
  getCommand_self_trade,
  getCommand_self_info,
  getFutures_command_trade
} from "@/api/url";
export default {
  data() {
    return {
      rules: {
        match_name: [
          { required: true, message: "请选择匹配名称", trigger: "change" }
        ],
        match_id: []
      },
      egForm: {
        match_name: "",
        creator: 1,
        match_id: "",
        match_explain: ""
      },
      pages: {
        page: 1,
        pageSize: 20,
        pageTotal: 0
      },
      input: "",
      textarea3: "",
      spotData: [],
      dialogVisible: false,
      dialogVisible_addrow: false,
      tableData: [],
      tableData_addrow: [],
      selectData: [],
      datas: [],
      id: this.$route.query.id,
      command_type_datas: [
        {
          value: 1,
          label: "现货期货套期"
        },
        {
          value: 2,
          label: "现货现货套期"
        },
        {
          value: 3,
          label: "现货期权套期"
        },
        {
          value: 4,
          label: "期货期货套利"
        },
        {
          value: 5,
          label: "现货单边"
        },
        {
          value: 6,
          label: "期货单边"
        }
      ],
      directionSelect: [
        {
          value: 1,
          label: "采购"
        },
        {
          value: 2,
          label: "销售"
        },
        {
          value: 3,
          label: "买入"
        },
        {
          value: 4,
          label: "卖出"
        }
      ],
      kp: [
        {
          value: 0,
          label: "开仓"
        },
        {
          value: 1,
          label: "平仓"
        },
        {
          value: 3,
          label: "平今仓"
        },
        {
          value: 4,
          label: "平昨仓"
        }
      ],
      bz: [
        {
          value: "CNY",
          label: "人民币"
        },
        {
          value: "USD",
          label: "美元"
        },
        {
          value: "EUR",
          label: "欧元"
        },
        {
          value: "GBP",
          label: "英镑"
        }
      ],
      dw: [
        {
          value: 0,
          label: "吨"
        },
        {
          value: 1,
          label: "千克"
        },
        {
          value: 2,
          label: "桶"
        },
        {
          value: 3,
          label: "立方米"
        },
        {
          value: 4,
          label: "张"
        },
        {
          value: 5,
          label: "克"
        }
      ],
      options1: [
        {
          value: 1,
          label: "现货期货套期"
        },
        {
          value: 2,
          label: "现货现货套期"
        },
        {
          value: 3,
          label: "现货期权套期"
        },
        {
          value: 4,
          label: "期货期货套利"
        },
        {
          value: 5,
          label: "现货单边"
        },
        {
          value: 6,
          label: "期货单边"
        }
      ],
      currentRow: null,
      index_s: "",
      name_instrument: "",
      addDatas: [],
      delDatas: [],
      updDatas: []
    };
  },
  created() {
    this.selectShuju();
  },
  methods: {
    tableRow({ row, rowIndex }) {
      row.index = rowIndex;
    },
    selectShuju() {
      var data = {
        match_id: this.id
      };
      getCommand_self_trade(data).then(res => {
        this.spotData = res.result.results;
        this.spotData.forEach(item => {
          (item.zhyj = 0), (item.match_id = this.egForm.match_id);
        });
      });
      getCommand_self_info(data).then(res => {
        this.egForm.match_name = res.result.results[0].match_name;
        this.egForm.match_id = res.result.results[0].match_id;
        this.egForm.match_explain = res.result.results[0].match_explain;
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    row_select_fn() {
      // console.log(this.currentRow);
      if (this.name_instrument == "name") {
        this.spotData[this.index_s].productName = this.currentRow.productName;
      } else {
        this.spotData[this.index_s].instrument = this.currentRow.instrument;
      }
      this.dialogVisible = false;
    },
    // 多选
    handleSelectionChange(selection) {
      this.datas = selection;
    },
    // handleSelectionChange_dialogVisible(selection) {
    //   this.selectData = selection;
    // },
    submit_fn() {
      this.$refs["egForm"].validate(valid => {
        if (valid) {
      //添加判断条件
      if (this.datas.length < 1) {
        this.$message({
          message: "至少选择二条指令明细",
          type: "warning"
        });
      } else {
        if (this.egForm.match_name == "") {
          this.$message({
            message: "请输入匹配名称",
            type: "warning"
          });
        } else {
          // 这里的逻辑是 拿到数据 我都加了个zhyj字段 0为原生数据 1为自己加的数据
          // 正常的逻辑 选中的所以数据-新增-删除=修改的数据
          //这里我用的是 修改只可能是原生数据  所以选中的数据里的原生数据就是修改数据 （因为在删除的时候，删元素数据之后，你就选不了你删除的数据了）
          // this.datas.forEach(item => {
          //   if (
          //     item.volume != "" &&
          //     (item.price != "") & (item.command_name != "")
          //   ) {
          //     this.$message({
          //       message: "指令名称,手数，成交价不能为空",
          //       type: "warning"
          //     });
          //     return;
          //   } else {
          //     if (item.zhyj == 0) {
          //       this.updDatas.push(item);
          //     }
          //   }
          // });
          for (var ins = 0; ins < this.datas.length; ins++) {
            if (
              this.datas[ins].volume == "" ||
              this.datas[ins].price == "" ||
              this.datas[ins].command_name == ""
            ) {
              this.$message({
                message: "指令名称,手数，成交价不能为空",
                type: "warning"
              });
              return;
            } else {
              if (this.datas[ins].zhyj == 0) {
                this.updDatas.push(this.datas[ins]);
              }
            }
              if (this.datas[ins].direction == '买入') {
                num += this.datas[ins].volume;
              } else {
                num_fan += this.datas[ins].volume;
              }
          }
          let copyDatas = this.datas[0];
          let num = 0;
          let num_fan = 0;
          for (var i = 1; i < this.datas.length; i++) {
            if (copyDatas.productName != this.datas[i].productName) {
              this.$message({
                message: "品名不一样",
                type: "warning"
              });
              return;
            } else if (copyDatas.instrument != this.datas[i].instrument) {
              this.$message({
                message: "合约不一样",
                type: "warning"
              });
              return;
            } else if (copyDatas.offset_flag != this.datas[i].offset_flag) {
              this.$message({
                message: "开/平不一样",
                type: "warning"
              });
              return;
            } else if (copyDatas.price != this.datas[i].price) {
              this.$message({
                message: "成交价不一样",
                type: "warning"
              });
              return;
            } else if (
              copyDatas.commodity_unit != this.datas[i].commodity_unit
            ) {
              this.$message({
                message: "单位不一样",
                type: "warning"
              });
              return;
            }
          }
          if (num != num_fan) {
            this.$message({
              message: "手数不一样",
              type: "warning"
            });
            return;
          }
          var LData = {
            operation: "MOD",
            self_info: this.egForm,
            trade_info: {
              ADD: this.addDatas,
              DEL: this.delDatas,
              MOD: this.updDatas
            }
          };
          command_self_info(LData).then(res => {
            this.$message({
              message: res.result,
              type: "success"
            });
            // this.$nextTick();
            // this.$router.replace("/refresh");
            this.$router.push('/hedging_strategy/order_management')
          }).catch(err=>{
             this.$message.error(err.msg);
          });
        }
      }
       } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    delRow_fn() {
      if (this.datas.length != 0) {
        for (let i = 0; i < this.spotData.length; i++) {
          for (let indexss = 0; indexss < this.datas.length; indexss++) {
            if (this.spotData[i].index == this.datas[indexss].index) {
              this.spotData.splice(i, 1);
              if (this.datas[indexss].zhyj == 0) {
                this.delDatas.push(this.datas[indexss]);
              } else {
                for (let its = 0; its < this.addDatas.length; its++) {
                  if (this.datas[indexss].index == this.addDatas[its].index) {
                    this.addDatas.splice(its, 1);
                  }
                }
              }
            }
          }
        }
      }
    },
    addRow_fn() {
      getFutures_command_trade().then(res => {
        this.dialogVisible_addrow = true;
        this.tableData_addrow = res.result.results;
        this.pages.pageTotal = res.result.count;
      });
    },
    select_fnn(index, zfc) {
      this.index_s = index;
      this.name_instrument = zfc;
      this.pages.page=1
      getFutures_command_trade(this.pages).then(res => {
        this.dialogVisible = true;
        this.tableData = res.result.results;
        this.pages.pageTotal = res.result.count;
      });
    },
    handlePaginationChange(val) {
      var data = {
        page: val
      };
      getFutures_command_trade(data).then(res => {
        this.dialogVisible = true;
        this.tableData = res.result.results;
        this.pages.pageTotal = res.result.count;
      });
    },
    handlePaginationChange_addrow(val) {
      var data = {
        page: val
      };
      getFutures_command_trade(data).then(res => {
        this.dialogVisible_addrow = true;
        this.tableData_addrow = res.result.results;
        this.pages.pageTotal = res.result.count;
      });
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    handleCurrentChange_addrow(val) {
      this.currentRow_addrow = val;
    },
    addrow_select_fn() {
      this.currentRow_addrow.zhyj = 1;
      // this.currentRow_addrow.name = this.currentRow_addrow.name.name;
      this.currentRow_addrow.match_id = this.egForm.match_id;
      this.addDatas.push(this.currentRow_addrow);
      this.spotData.push(this.currentRow_addrow);
      this.dialogVisible_addrow = false;
    }
  }
};
</script>
<style lang="scss">
.resizeNone {
  .el-textarea__inner {
    //el_input中的隐藏属性
    resize: none; //主要是这个样式
  }
}
</style>
